package com.ukee.birthday.common.utils;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.UUID;

import static com.ukee.birthday.config.WebConfig.FILEPATH;
/**
 * 生成二维码
 *
 * @author yan
 */
public class QrCodeUtils {

	public static String generateQRCodeImage(String text, int width, int height) throws WriterException, IOException {
		QRCodeWriter qrCodeWriter = new QRCodeWriter();
		
		HashMap<EncodeHintType, Object> hints = new HashMap<>();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
        
		BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints);
		
        String filename = UUID.randomUUID() + ".png";
        File dest = new File(FILEPATH + filename);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        
		Path path = FileSystems.getDefault().getPath(FILEPATH + filename);
		
		MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
		
		return filename;
	}

}
